package com.czk.netty.nio.selector;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

/**
 * nio服务器的实现
 *
 * @Author:ChenZhangKun
 * @Date: 2021/1/11 22:28
 */
public class NioServer {
    public static void main(String[] args) throws IOException {
        // 创建通道
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        // 得到一个selector
        Selector selector = Selector.open();
        // 绑定端口
        serverSocketChannel.bind(new InetSocketAddress(6666));
        // 设置为非阻塞
        serverSocketChannel.configureBlocking(false);
        // 将serverSocket注册到selector,关心时间为Accept
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
        // 循环等待客户端连接
        while (true) {
            // 阻塞方法等待1s,查看是否有连接
            if (selector.select(1000) == 0) {
                // 没有事件发生
                System.out.println("服务器等待1s无连接");
                continue;
            }
            // 此时大于0，获取到了关注事件
            // 反向获取通道
            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            Iterator<SelectionKey> iterator = selectionKeys.iterator();
            while (iterator.hasNext()) {
                // 获取SelectionKey
                SelectionKey selectionKey = iterator.next();
                // 查看事件类型
                if (selectionKey.isAcceptable()) {
                    // 如果是OP_ACCEPT,相当于一个客户端来链接我
                    // 生成一个socketChannel
                    SocketChannel socketChannel = serverSocketChannel.accept();
                    // 指定为非阻塞模型
                    socketChannel.configureBlocking(false);
                    // 将其注册到selector
                    // 同时给channel关联一个buffer
                    socketChannel.register(selector, SelectionKey.OP_READ, ByteBuffer.allocate(1024));
                }
                if (selectionKey.isReadable()) {
                    // 反向获取对应的channel
                    SocketChannel channel = (SocketChannel) selectionKey.channel();
                    // 拿到buffer
                    ByteBuffer buffer = (ByteBuffer) selectionKey.attachment();
                    // 读取数据
                    channel.read(buffer);
                    System.out.println("客户度发送的数据  " + new String(buffer.array()));
                }
                // 手动后移除当前的key,否则会重复操作
                iterator.remove();
            }

        }
    }
}
